package com.third.customer.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.third.customer.model.dao.AreaDao;
import com.third.customer.model.dao.CustomerDao;
import com.third.customer.model.dao.param.AreaParam;
import com.third.customer.model.tables.Area;
import com.third.customer.service.AreaService;
import com.third.customer.service.data.AreaReq;
import com.third.customer.service.exception.ThirdBadRequestException;
import com.third.customer.service.exception.ThirdNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

/**
 * Created by hehuaichun on 2020/5/23.
 */
@Service
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaDao areaDao;

    @Autowired
    private CustomerDao customerDao;

    @Override
    public Page<Area> list(AreaParam param) {
        return areaDao.query(param);
    }

    @Override
    public Area getById(Long companyId, Long areaId) {
        return areaDao.getById(companyId, areaId).orElseThrow(() ->
                new ThirdNotFoundException("地区信息不存在!"));
    }

    @Override
    public Area create(Long companyId, AreaReq req) {
        Optional<Area> optional = areaDao.getByAreaName(companyId, req.getCounty(), req.getCommunity());
        if (optional.isPresent()) {
            throw new ThirdBadRequestException("新增地区信息已经存在!");
        }
        Area area = new Area();
        area.setCompanyId(companyId);
        area.setCommunity(req.getCommunity());
        area.setCounty(req.getCounty());
        areaDao.insert(area);
        return area;
    }

    @Override
    public Area modify(Long companyId, Long areaId, AreaReq req) {
        getById(companyId, areaId);
        Area area = new Area();
        area.setId(areaId);
        area.setCounty(req.getCounty());
        area.setCommunity(req.getCommunity());
        areaDao.update(area);
        return area;
    }

    @Override
    public boolean delete(Long companyId, Long areaId) {
        getById(companyId, areaId);
        if (!CollectionUtils.isEmpty(customerDao.getByAreaId(companyId, areaId))) {
            throw new ThirdBadRequestException("当前地区配置还有客户在使用,不允许删除");
        }
        return areaDao.delete(areaId);
    }

    @Override
    public List<Area> getByIds(Long companyId, List<Long> areaIds) {
        return areaDao.getByIds(companyId, areaIds);
    }
}
